package start.jdbccursor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CursorQueryExample {
    private static final int BATCH_SIZE = 10000*100;
    private static final String URL = "jdbc:mysql://localhost:3306/study";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            // 建立数据库连接
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

            // 设置查询语句，使用游标查询
            String query = "SELECT * FROM t_order t where t.create_time >= '2022-12-04 02:59:47' and t.create_time <= '2050-12-04 02:59:47' order by id ASC";
            statement = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
            statement.setFetchSize(Integer.MIN_VALUE);
            //statement.setFetchSize(1000);

            // 执行查询，使用游标批量获取数据
            resultSet = statement.executeQuery();

            int count = 0;
            while (resultSet.next()) {
                // 处理每一条记录，这里只是简单地打印记录的id
                long id = resultSet.getLong("id");
                System.out.println("id: " + id);

                count++;

                // 每BATCH_SIZE条记录，显示进度
                if (count % BATCH_SIZE == 0) {
                    System.out.println("Processed " + count + " records.");
                    Thread.sleep(1000*2);
                }
            }

            System.out.println("Processed " + count + " records in total.");

        } catch (SQLException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
